package com.cby.code.net;


import com.cby.code.net.engine.BaseEngine;
import com.cby.code.net.engine.DefaultEngine;
import com.cby.code.net.listener.ResponseListener;
import com.cby.code.net.policy.RetryPolicy;

import java.util.Map;

/**
 * @description: 网络搬运工：数据请求的对外总接口
 * @author: ChenBaoYang
 * @createDate: 2022/2/15 2:26 下午
 */
public class NetBrickPorter {

    /** 请求构建对象 */
    private final Request.Builder requestBuilder;
    /** 请求参数构建对象 */
    private final RequestParam.Builder paramBuilder;

    private ResponseListener listener;

    private NetBrickPorter(){
        paramBuilder = new RequestParam.Builder();
        requestBuilder = new Request.Builder();
    }

    public static NetBrickPorter getDefault(){
        return new NetBrickPorter();
    }

    public NetBrickPorter setBaseUrl(String url) {
        requestBuilder.setUrl(url);
        return this;
    }

    public NetBrickPorter setMethod(int method) {
        requestBuilder.setMethod(method);
        return this;
    }

    public NetBrickPorter setPathSegment(String hostPath) {
        requestBuilder.setPathSegment(hostPath);
        return this;
    }

    public NetBrickPorter setRetryPolicy(RetryPolicy policy) {
        requestBuilder.setRetryPolicy(policy);
        return this;
    }

    public NetBrickPorter addParam(String key, Object value) {
        paramBuilder.addParam(key, value);
        return this;
    }

    public NetBrickPorter addAllParam(Map<String, Object> paramMap) {
        if(paramMap != null) {
            for(Map.Entry<String, Object> param: paramMap.entrySet()) {
                paramBuilder.addParam(param.getKey(), param.getValue());
            }
        }
        return this;
    }

    public NetBrickPorter addAllHeader(Map<String, String> headerMap) {
        if(headerMap != null) {
            for (Map.Entry<String, String> header: headerMap.entrySet()) {
                paramBuilder.addHeader(header.getKey(), header.getValue());
            }
        }
        return this;
    }

    public NetBrickPorter addHeader(String key, String value) {
        paramBuilder.addHeader(key, value);
        return this;
    }

    public NetBrickPorter setResponseListener(ResponseListener listener) {
        this.listener = listener;
        return this;
    }

    public void start() {
        RequestParam requestParam = paramBuilder.build();
        Request request = requestBuilder.setRequestParam(requestParam).build();
        BaseEngine engine = new DefaultEngine(request);
        engine.setListener(listener);
        engine.doWork();
    }
}
